import { defineStore } from "pinia";

// 定义 store
const useCartStore = defineStore('shoppingcart', {
    state() {
        return {
            cart: [] as Goods[], // 购物车数组结构
        }
    },
    actions: {
        /* 
            加入购物车
        */
        addToCart(payload: Goods) {
            // 加入购物车后，判断购物车数组中是否存在当前商品数据，如存在则累加
            const has = this.cart.some(curr => curr.id === payload.id)
            if (has) {
                this.cart.forEach(curr => {
                    if (curr.id == payload.id) {
                        curr.amount = (curr.amount as number) + (payload.amount ?? 1)
                    }
                })
            } else { // 如不存在则将商品添加到数组中
                this.cart.push({
                    ...payload,
                    amount: payload.amount ?? 1,
                    // 加入购物车的商品默认被选中
                    checked: true
                })
            }
        },
        /* 
            删除购物车中的商品
        */
        removeFromCart(id: string) {
            this.cart = this.cart.filter(curr => curr.id !== id)
        },

        /* 
             全选或取消全选
        */
        checkAll(checked: boolean) {
            this.cart.forEach(curr => {
                curr.checked = checked
            })
        },
    },
    getters: {
        /* 
            是否全选
        */
        allChecked(state) {
            return state.cart.every(curr => curr.checked)
        },
        /* 
            计算合计金额
        */
        totalMoney(state) {
            return state.cart.reduce((sum, curr) => {
                if (curr.checked) {
                    sum += curr.price * (curr.amount ?? 1)
                }
                return sum
            }, 0) * 100
        }
    },
    // 数据持久化
    persist: {}
})

export default useCartStore